package com.cn.netty.customize.handler;

import com.cn.netty.customize.BusinessMeassage;
import com.cn.netty.customize.Codec;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 解码
 * 字节转码成Message实体
 */
@Slf4j
public class DecodeHandler extends ByteToMessageDecoder {

  @Override
  protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
//    String str = in.toString(StandardCharsets.UTF_8); //ByteBuf.toString()方法，不会移动 WriteIndex和ReadIndex 索引

    int readLen = in.readableBytes();
    byte[] readB = new byte[readLen];
    ByteBuf byteBuf = in.readBytes(readB);

    String str = new String(readB, StandardCharsets.UTF_8);
    log.debug(str);

    BusinessMeassage businessMeassage = Codec.getBusinessMeassage(str);
    out.add(businessMeassage);
  }

}
